<template>
  <div class="shell">
    <!-- 顶部logo区域 -->
    <div class="top">
      <div class="logo">
        <img src="@/assets/CodeRealm.png" />
      </div>
      <div class="l-name"><span>AgriHub</span><sup>®</sup></div>
    </div>
    <div class="identity">
        <div class="farmer" :class="{ active: identity === 0 }" @click="switchIdentity(0)">农户</div>
        <div class="dealer" :class="{ active: identity === 1 }" @click="switchIdentity(1)">经销商</div>
    </div>
    <!-- 中部内容区域 -->
    <div class="middle">
      <!-- 左侧表单 -->
      <div class="m-left">
        <div class="inp">
          <div class="label-error-container">
            <span class="label">用户名</span>
            <span v-if="errors.username && Form.username !== ''" class="error-message">{{ errors.username }}</span>
          </div>
          <input
            v-model="Form.username"
            spellcheck="false"
            placeholder="请输入您的用户名"
            type="text"
            :class="{'input-error': errors.username && Form.username !== '', 'input-success': validStatus.username && Form.username !== ''}"
          />
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">名称</span>
            <span v-if="errors.nickname && Form.nickname !== ''" class="error-message">{{ errors.nickname }}</span>
          </div>
          <input
            v-model="Form.nickname"
            spellcheck="false"
            placeholder="请输入您所期望的称呼"
            type="text"
            :class="{'input-error': errors.nickname && Form.nickname !== '', 'input-success': validStatus.nickname && Form.nickname !== ''}"
          />
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">密码</span>
            <span v-if="errors.password && Form.password !== ''" class="error-message">{{ errors.password }}</span>
          </div>
          <input
            v-model="Form.password"
            type="password"
            placeholder="请输入6~15位字母、数字，还可包含特殊字符"
            :class="{'input-error': errors.password && Form.password !== '', 'input-success': validStatus.password && Form.password !== ''}"
          />
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">确认密码</span>
            <span v-if="errors.conf_password && Form.conf_password !== ''" class="error-message">{{ errors.conf_password }}</span>
          </div>
          <input
            v-model="Form.conf_password"
            type="password"
            placeholder="请再次输入密码以确认"
            :class="{'input-error': errors.conf_password && Form.conf_password !== '', 'input-success': validStatus.conf_password && Form.conf_password !== ''}"
          />
        </div>
        
        <div class="inp">
          <div class="label-error-container">
            <span class="label">邮箱</span>
            <span v-if="errors.mail && Form.mail !== ''" class="error-message">{{ errors.mail }}</span>
          </div>
          <input
            v-model="Form.mail"
            spellcheck="false"
            type="text"
            placeholder="请输入有效的邮箱地址"
            :class="{'input-error': errors.mail && Form.mail !== '', 'input-success': validStatus.mail && Form.mail !== ''}"
          />
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">电话号码</span>
            <span v-if="errors.phone && Form.phone !== ''" class="error-message">{{ errors.phone }}</span>
          </div>
          <input
            v-model="Form.phone"
            spellcheck="false"
            type="text"
            placeholder="请输入以1开头的11位有效电话号码"
            :class="{'input-error': errors.phone && Form.phone !== '', 'input-success': validStatus.phone && Form.phone !== ''}"
          />
        </div>
        <div class="inp">
          <div class="label-error-container">
            <span class="label">地址</span>
            <span v-if="errors.address && Form.address !== ''" class="error-message">{{ errors.address }}</span>
          </div>
          <input
            v-model="Form.address"
            spellcheck="false"
            type="text"
            placeholder="请输入地址"
            :class="{'input-error': errors.address && Form.address !== '', 'input-success': validStatus.address && Form.address !== ''}"
            @keyup.enter="regUser"
          />
        </div>
        <div class="bnt">
          <button @click="regUser" :disabled="isSubmitting">{{ isSubmitting ? '注册中...' : '注册' }}</button>
        </div>
      </div>
      <!-- 右侧介绍 -->
      <div class="m-right">
        <span class="r-top">为什么加入AgriHub</span>
        <span class="r-bottom">1.轻松上架和销售农产品</span>
        <span class="r-bottom">2.加入AgriHub农业社区</span>
        <span class="r-bottom">3.实时获取农业资讯与技术支持</span>
        <span class="r-bottom">4.随时随地管理农产品</span>
        <span class="r-bottom">5.参与农业活动与培训</span>
        <span class="r-bottom">6.获取智能推荐与数据分析</span>
        <div class="im">
          <!-- <img src="@/assets/CodeRealm.png" /> 
          <span>AgriHub</span> -->
        </div>
      </div>

    </div>
    <!-- 底部跳转 -->
    <div class="bottom">
      <div>
        <span style="cursor: pointer" class="underline" @click="toLogin">已注册，点击登录。</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useMainStore } from '@/stores'
import { ElLoading } from 'element-plus'
import { ElMessage } from 'element-plus'

const router = useRouter()
const mainStore = useMainStore()
const $axios = inject('$axios')
const $tools = inject('$tools')

const identity = ref(0)

// 切换身份函数
function switchIdentity(type) {
  identity.value = type
}

const Form = ref({
  username: '',
  nickname: '',
  password: '',
  conf_password: '',
  mail: '',
  phone: '',
  address: '',
})

// 表单验证配置
const validationConfig = {
  username: {
    rule: /^[a-zA-Z0-9_]{6,20}$/,
    errorMsg: '用户名长度6-20个字符，只允许字母、数字和下划线'
  },
  nickname: {
    rule: /^.{2,20}$/,
    errorMsg: '名称长度2-20个字符'
  },
  password: {
    rule: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\W]{6,15}$/,
    errorMsg: '密码长度6-15个字符，必须包含字母和数字'
  },
  conf_password: {
    // 特殊处理，在验证函数中单独处理
    errorMsg: '两次输入的密码不一致'
  },
  mail: {
    rule: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
    errorMsg: '请输入有效的邮箱地址'
  },
  phone: {
    rule: /^1\d{10}$/,
    errorMsg: '请输入以1开头的11位有效电话号码'
  },
  address: {
    rule: /^.{5,100}$/,
    errorMsg: '地址长度5-100个字符'
  }
}

// 错误信息
const errors = reactive({
  username: '',
  nickname: '',
  password: '',
  conf_password: '',
  mail: '',
  phone: '',
  address: ''
})

// 验证状态
const validStatus = reactive({
  username: false,
  nickname: false,
  password: false,
  conf_password: false,
  mail: false,
  phone: false,
  address: false
})

// 简化的验证函数
function validate(field, value) {
  // 空值检查
  if (!value) {
    errors[field] = '此项不能为空'
    validStatus[field] = false
    return
  }
  
  // 确认密码特殊处理
  if (field === 'conf_password') {
    validStatus[field] = value === Form.value.password
    errors[field] = validStatus[field] ? '' : validationConfig[field].errorMsg
    return
  }
  
  // 其他字段通用验证
  if (validationConfig[field].rule) {
    validStatus[field] = validationConfig[field].rule.test(value)
    errors[field] = validStatus[field] ? '' : validationConfig[field].errorMsg
  }
  
  // 如果密码改变，重新验证确认密码
  if (field === 'password' && Form.value.conf_password) {
    validate('conf_password', Form.value.conf_password)
  }
}

// 监听表单字段变化
watch(() => Form.value.username, (val) => validate('username', val))
watch(() => Form.value.nickname, (val) => validate('nickname', val))
watch(() => Form.value.password, (val) => validate('password', val))
watch(() => Form.value.conf_password, (val) => validate('conf_password', val))
watch(() => Form.value.mail, (val) => validate('mail', val))
watch(() => Form.value.phone, (val) => validate('phone', val))
watch(() => Form.value.address, (val) => validate('address', val))

// 页面跳转函数
function toLogin() {
  router.push('/login')
}

// 防抖标志
const isSubmitting = ref(false)

// 注册函数
async function regUser() {
  // 防止重复提交
  if (isSubmitting.value) {
    return
  }
  // 验证所有字段
  for (let key in Form.value) {
    validate(key, Form.value[key])
  }
  
  // 检查所有字段是否验证通过
  const isValid = Object.values(validStatus).every(status => status === true)
  
  // 表单验证
  if (!isValid) {
    $tools.alertMsg('表单验证未通过，请检查输入', 'error', 2000)
    return
  }
  isSubmitting.value = true

  const loadingInstance = ElLoading.service({
    text: '注册中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const response = await $axios.post('/user/reg', {
      user_name: Form.value.username,
      user_pwd: Form.value.password,
      user_email: Form.value.mail,
      user_phone: Form.value.phone,
      user_address: Form.value.address,
      role_name: (identity.value == "0")?"farmer":"dealer",
      nick_name: Form.value.nickname
    })
    console.log(response)
    if (response.data.code === 200) {
      $tools.alertMsg('注册成功', 'success')
      setTimeout(() => {
        router.push('/login')
        isSubmitting.value = false
      }, 1000)
    } else {
      $tools.alertMsg(response.data.msg || '注册失败，请稍后重试', 'error',2000)
      isSubmitting.value = false
    }
  } catch (error) {
    console.error('注册错误:', error)
    $tools.alertMsg('注册失败，请稍后重试', 'error',2000)
    isSubmitting.value = false
  } finally {
    loadingInstance.close()
  }
}
</script>

<style lang="less" scoped>
.underline {
  text-decoration: underline;
}
.shell {
  padding: 0px 40px 30px 0px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 860px;
  background-color: #fbfbfb;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  // 顶部菜单
  .menu {
    text-align: right;
    margin-right: -40px;
    .close-icon {
      cursor: pointer;
      width: 17px;
      height: 17px;
      padding: 8px;
      color: #788a92;
      &:hover {
        background-color: red;
        color: #e0e1e6;
      }
    }
  }
  .top,
  .middle,
  .identity,
  .bottom {
    padding-left: 40px;
  }
  // 顶部样式
  .top {
    display: flex;
    align-items: center;
    color: #e0e1e6;
    margin: 20px 0px 6px 0px;
    .logo {
      img {
        width: 44px;
        height: 44px;
      }
    }
    .l-name {
      background: linear-gradient(to right bottom, rgb(77, 220, 58), rgb(147, 248, 88));
      -webkit-background-clip: text;
      background-clip: text;
      color: transparent;
      margin-left: 4px;
      span {
        font-size: 24px;
        font-weight: bold;
        letter-spacing: 3px;
      }
      sup {
        font-size: 9px;
        vertical-align: top;
      }
    }
  }
  .identity{
        display: flex;
        justify-content: space-between;
        width: 420px;
        margin: 10px 0px;
        div{
            width: 42%;
            height: 40px;
            line-height: 40px;
            text-align: center;
            background-color: #eee;
            color: #666;
            font-weight: bold;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
            &:hover {
                background-color: #e0e0e0;
            }
            &.active {
                background-color: #3ac21b;
                color: #fff;
            }
        }
    }
  // 中部样式
  .middle {
    display: flex;
    justify-content: space-between;
    .m-left,
    .m-right {
      display: flex;
      flex-direction: column;
    }
    .m-left {
      .inp {
        text-align: left;
        display: flex;
        flex-direction: column;
        margin-top: 11px;
        .label-error-container {
          display: flex;
          justify-content: space-between;
        }
        .label {
          font-size: 12px;
          color: #afafaf;
        }
        input {
          background-color: #f9f9f9;
          width: 384px;
          height: 38px;
          border-radius: 2px;
          color: #222;
          outline: none;
          border: 1px solid #ddd;
          text-indent: 10px;
          font-size: 14px;
          transition: border 0.3s;
          &.input-error {
            border: 1px solid #ff4d4f;
          }
          &.input-success {
            border: 1px solid #52c41a;
          }
        }
        
        .error-message {
          color: #ff4d4f;
          font-size: 12px;
        }

      }
      .memory {
        margin-top: 10px;
        display: flex;
        align-items: center;
        cursor: pointer;
        user-select: none;
        span {
          vertical-align: middle;
          font-size: 12px;
          color: #afafaf;
        }
        .sel-icon {
          margin-right: 6px;
          width: 15px;
          height: 15px;
          padding: 2px;
          color: #32353C;
          border: 1px solid #999;
          border-radius: 2px;
        }
        &:hover .sel-icon {
          background-color: #393c44;
          color: #393c44;
        }
      }
      .bnt {
        margin-top: 22px;
        button {
          cursor: pointer;
          width: 280px;
          height: 44px;
          color: #fff;
          border: none;
          outline: none;
          font-size: 15px;
          border-radius: 2px;
          background-image: linear-gradient(to right, rgb(77, 220, 58), rgb(147, 248, 88));
          &:hover {
              background-image: linear-gradient(to right, rgb(77, 220, 58), rgb(58, 220, 99) 30%,rgb(147, 248, 88));
          }
        }
      }
    }
    .m-right {
      display: flex;
      flex-direction: column;
      text-align: left;
      margin-left: 30px;
      margin-top: 20px;
      span {
        font-size: 16px;
        height: 32px;
        line-height: 32px;
        color: #888;
      }
      .r-top {
        color: #19ff38;
        font-size: 20px;
      }
      .im {
        width: 300px;
        height: 250px;
        background-image: url(@/assets/reg.png);
        background-size: cover;
        background-position: center;
        border-radius: 10px;
        margin: 6px 0px 8px 0px;
        display: flex;
        flex-direction: column;
        align-items: center;
        // justify-content: center;
        img{
          width: 50px;
          height: 50px;
          padding: 6px;
        }
      }
    }
  }
    // 底部样式
    .bottom {
      padding-top: 30px;
      font-size: 12px;
      color: #777;
      display: flex;
      justify-content: space-between;
    }
}
</style>